import { defineStore } from "pinia";
import { ref } from "vue";
import { addMessage, getMessagesByChat } from "@/utils/indexedDb";
export interface ChatMessage {
  id?: number; // IndexedDB 自动生成的主键
  senderId: number;
  senderName: string;
  receiverId?: number; // 私聊消息才有
  groupId?: number; // 群聊消息才有
  type: "PRIVATE" | "GROUP";
  content: string;
  timestamp: string; // 时间戳
}

export const useMessageStore = defineStore("message", {
  state: () => ({
    messages: [] as ChatMessage[],
    currentChatId: null as number | null,
    currentChatType: null as "PRIVATE" | "GROUP" | null,
  }),

  actions: {
    setCurrentChat(id: number, type: "PRIVATE" | "GROUP") {
      this.currentChatId = id;
      this.currentChatType = type;
    },

    async saveMessage(message: ChatMessage) {
      await addMessage(message);

      const currentUserId = Number(localStorage.getItem("user_id"));

      if (this.currentChatType === message.type) {
        if (
          message.type === "PRIVATE" &&
          ((this.currentChatId === message.receiverId &&
            message.senderId === currentUserId) ||
            (this.currentChatId === message.senderId &&
              message.receiverId === currentUserId))
        ) {
          this.messages = [...this.messages, message]; // ✅ 用展开数组触发响应式
        } else if (
          message.type === "GROUP" &&
          this.currentChatId === message.groupId
        ) {
          this.messages = [...this.messages, message];
        }
      }
    },
    setMessages(list: ChatMessage[]) {
      this.messages = list;
    },
  },
});
